import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Modal, Form, Input } from 'antd';

const { Item } = Form;

@connect(({ loading }) => ({
  loading: !!loading.effects['user/changeProfile'],
}))
@Form.create()
export default class ModalChangeEmail extends PureComponent {
  componentDidMount() {
    const { form, email } = this.props;
    form.setFieldsValue({ email });
  }

  handleSubmit = () => {
    const { form, dispatch, onSuccess } = this.props;
    form.validateFields((err, { email }) => {
      if (!err) {
        dispatch({
          type: 'user/changeProfile',
          payload: {
            params: {
              params: {
                email,
              },
            },
            onSuccess: () => {
              onSuccess();
            },
          },
        });
      }
    });
  };

  render() {
    const { visible, onCancel, form, loading } = this.props;

    return (
      <Modal
        title="修改E-mail"
        visible={visible}
        onCancel={onCancel}
        onOk={this.handleSubmit}
        confirmLoading={loading}
      >
        <Form hideRequiredMark>
          <Item label="E-mail">
            {form.getFieldDecorator('email', {
              rules: [
                {
                  required: true,
                  message: '电子邮箱不能为空！',
                },
                {
                  type: 'email',
                  message: '邮箱地址格式错误！',
                },
              ],
            })(<Input />)}
          </Item>
        </Form>
      </Modal>
    );
  }
}
